package user.config;


import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import commons.SmsrepaymentUtils;
import entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import user.service.*;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

//自动还款定时任务
@Component
public class MyTask {
    @Autowired
    IUserInfoService iUserInfoService;
    @Autowired
    ICredit iCredit;
    @Autowired
    IBillService iBillService;
    @Autowired
    IBankcardService iBankcardService;
    @Autowired
    IRepaymentService iRepaymentService;
    @Autowired
    UserService userService;

    @Scheduled(cron = "0 0 9 * * ?")
    //根据用户设置了自动还款日期的自动还款
    public void task() {
        System.out.println("开始还款");
        Calendar cal = Calendar.getInstance();
        int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
        int month = cal.get(Calendar.MONTH) + 1;    //获取当前月份
        List<CcmsUserInfo> list = iUserInfoService.getUserByDate(dayOfMonth+"");//得到所有用户列表
        System.out.println(list);
        for (CcmsUserInfo userInfo : list) { //遍历用户
            int repaymentDate = 0;
            if (userInfo.getRepayment() != null && !userInfo.getRepayment().equals("")) {  //判断用户是否设置还款日期
                repaymentDate = Integer.parseInt(userInfo.getRepayment());//用户设置的自动还款日期
            }
            if (repaymentDate == dayOfMonth) {                             //判断当前日期是否为用户设置还款日期
                Integer userId = userInfo.getUserId();                      //得到用户id
                List<CcmsCredit> myCredit = iCredit.getMyCredit(userId); //获取该用户所有信用卡
                for (CcmsCredit credit : myCredit) {                      //遍历该用户信用卡
                    Integer creditId = credit.getCreditId();
                    List<CcmsBill> ccmsBills = iBillService.getbillByCreditId(creditId);//获取该信用卡所有账单
                    System.out.println("用户" + userId + "的信用卡" + creditId + "开始还款");
                    for (CcmsBill bill : ccmsBills) {
                        String billType = bill.getBillType();
                        String billCreateMonth = bill.getBillCreate();//获取账单日期
                        if (billCreateMonth.contains("-")) {  //判断日期中是否含有"-"
                            int substring = Integer.parseInt(billCreateMonth.substring(billCreateMonth.indexOf("-") + 1, billCreateMonth.length()));
                            if (substring == month) {//判断账单月份是否为当前月份
                                System.out.println("开始判断账单金额");
                                if ((bill.getBillAmount() + bill.getBillStage()) != 0) { //判断账单金额是否为0
                                    System.out.println("开始获取银行卡");
                                    List<CcmsBankcard> bankcards = iBankcardService.getBankcardByUserId(userId);//查询该用户所有银行卡
                                    int m = 0;
                                    for (CcmsBankcard bankcard : bankcards) {
                                        System.out.println("还款中");
                                        m++;
                                        if (bankcard.getBalance().compareTo(BigDecimal.valueOf(bill.getBillStage() + bill.getBillStage())) != -1) {
                                            BigDecimal newmoney = bankcard.getBalance().subtract(BigDecimal.valueOf(bill.getBillStage() + bill.getBillAmount()));//BigDecimal减法
                                            System.out.println("还款金额" + bill.getBillStage() + bill.getBillStage());
                                            bankcard.setBalance(newmoney);
                                            System.out.println(bankcard);
                                            int j = iBankcardService.deductmoney(bankcard);
                                            if (j > 0) {
                                                System.out.println(bankcard.getBankcardnum() + "扣款成功");
                                                int k = iBillService.updateBill(bill.getBillId(), BigDecimal.valueOf(bill.getBillStage() + bill.getBillAmount()));
                                                if (k > 0) {
                                                    System.out.println("账单处理成功");
                                                } else {
                                                    System.out.println("账单失败");
                                                }
                                                Date date = new Date();//获得系统时间.
                                                SimpleDateFormat sdf = new SimpleDateFormat(" yyyy-MM-dd HH:mm:ss ");
                                                Date time = null;
                                                String nowTime = sdf.format(date);
                                                try {
                                                    time = sdf.parse(nowTime);
                                                } catch (ParseException e) {
                                                    e.printStackTrace();
                                                }
                                                CcmsRepayment repayment = new CcmsRepayment();
                                                //设置还款明细的各个属性
                                                repayment.setCardnum(credit.getCardnum() + "");
                                                repayment.setNewBalance(BigDecimal.valueOf(bill.getBillAmount() + bill.getBillStage()));
                                                repayment.setRepayment(BigDecimal.valueOf(bill.getBillAmount() + bill.getBillStage()));
                                                repayment.setBankcardnum(bankcard.getBankcardnum());
                                                repayment.setRepaymentState("已还款");
                                                repayment.setBillId(bill.getBillId());
                                                repayment.setUserId(userInfo.getUserId());
                                                repayment.setRepaymentDate(time);
                                                int i = iRepaymentService.addRepayment(repayment);//将付款结果插入数据库
                                                if (i > 0) {
                                                    System.out.println("付款结果插入数据库成功");//可用日志记录

                                                } else {
                                                    System.out.println("发生异常,付款结果插入数据库失败");//可用日志记录
                                                }
                                                break;
                                            } else {
                                                System.out.println(bankcard.getBankcardnum() + "发生异常扣款失败,请联系客服");
                                            }
                                        } else {
                                            System.out.println(bankcard.getBankcardnum() + "余额不足!");
                                        }
                                        System.out.println("m的值为" + m);
                                        if (m == bankcards.size()) {
                                            System.out.println("发短信通知:银行卡余额不足,自动还款失败,请尽快还款,逾期将会产生额外利息,并影响个人征信");
                                        }
                                    }
                                } else {
                                    System.out.println("该账单没有欠款,无需还款");
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    //还款提醒
    @Scheduled(cron = "0 0 10 * * ?")
    public void warningtask() {
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;    //获取当前月份
        int day = cal.get(Calendar.DAY_OF_MONTH);
       String nowTime=year+"-"+month;
       List<CcmsBill> bills = iBillService.getBillByDate(nowTime);//得到当前月份所有未完成账单
        for (CcmsBill bill:bills){
          int repaytime = Integer.parseInt(bill.getBillRepaytime().substring(8,10));//得到当前账单最后还款日期
            System.out.println(repaytime);
            if(day==(repaytime-2)){ //判断当前日期是否最后还款日期前两天
                CcmsCredit credit = iCredit.getCreditById(bill.getCreditId());
                CcmsUserInfo user = iUserInfoService.getUserById(credit.getUserId());
                String userTel = user.getUserTel();
                SmsrepaymentUtils smsrepaymentUtils = new SmsrepaymentUtils();
                try {
                    SendSmsResponse sendSmsResponse = smsrepaymentUtils.sendSms(userTel,"billDueTowDay","SMS_204297250");
                } catch (ClientException e) {
                    e.printStackTrace();
                }
            }

        }
    }

   //@Scheduled(cron = "1 * * * * ?")
    public void task2() {
//        Date date = new Date();//获得系统时间.
//        SimpleDateFormat sdf = new SimpleDateFormat(" yyyy-MM");
//        String nowTime = sdf.format(date);
//        System.out.println(nowTime);
        warningtask();

    }

    //每月1号，将未出账单改成已出账单，并新增一个未出账单
    @Scheduled(cron = "0 0 8 1 * ?")
    public void billTask() {
        Date d = new Date();//获取服务器的时间。。。
        Calendar c = Calendar.getInstance();
        c.setTime(d);
        if (c.get(Calendar.DAY_OF_MONTH) == 1) //当前是1号
        {
            List<CcmsUser> allUser = userService.getAllUser();
            for (CcmsUser ccmsUser : allUser) {
                Integer userId = ccmsUser.getUserId();
                List<CcmsCredit> myCredit = iCredit.getMyCredit(userId);
                for (CcmsCredit ccmsCredit : myCredit) {
                    Integer creditId = ccmsCredit.getCreditId();
                    iBillService.updateCreate(creditId);
                }
            }
        }
    }
}
